package org.snusmumr.android.media.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.os.Environment;
import android.util.Log;

public class ImportParser {
	private static final String TOKEN_SEPARATOR = ";";
	private static final String TAG = ImportParser.class.getSimpleName();
	private BufferedReader buf;
	private String fileName;
	private ModelBuilder builder;
	private ArrayDataProvider dataProvider;
	private long fileSize;
	private int readLine = 0;
	
	public ImportParser(String fileName) {
		this.fileName = fileName;
	}
	
	private void init(String fileName) throws InvalidStorageStateException, FileNotFoundException {
		
		// check if SD-Card is accessible
		if(! Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			throw new InvalidStorageStateException("Invalid storage state: SD card is not mounted");
		
		File f = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
		this.fileSize = f.length();

		FileInputStream fileIS = new FileInputStream(f);
		this.buf = new BufferedReader(new InputStreamReader(fileIS));
	}
	
	private String[] parseNext() throws IOException {
		String line = buf.readLine();
		Log.d(TAG, "Read line: " + line);
		if(line == null) {
			// EOF
			close();
		}
		readLine++;
		return line != null ? line.split(TOKEN_SEPARATOR) : null;
	}
	
	private String[] initHeaders() throws InvalidFileFormatException {
		String[] firstLine = null;
		try {
			firstLine = parseNext();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(firstLine != null && firstLine.length > 0) {
			return firstLine;
		} else
			throw InvalidFileFormatException.getImportFileEmpty();
	}
	
	public ModelItem next() throws IOException, InvalidStorageStateException, InvalidFileFormatException, ParseException {
		if(buf == null) {
			init(fileName);
			String[] headers = initHeaders();
			dataProvider = new ArrayDataProvider(headers);
			builder = new ModelBuilder(dataProvider);
		}
		
		String[] fields = parseNext();
		if(fields != null) {
			dataProvider.setData(fields);
			return builder.buildItem();
		}
		
		return null;
	}
	
	public void close() throws IOException {
		if(buf != null)
			buf.close();
	}
	
	/**
	 * get currently processing file line number
	 * @return currently processing file line number
	 */
	public int getReadLine() {
		return readLine;
	}
}
